﻿using Aliyun.OSS;
using Md.Api.DDD;
using Md.Api.Model.Util.Oss.Request;

namespace Md.Util.Service.Oss;
/// <summary>
/// 阿里云OSS文件上传服务
/// 相关文档：https://help.aliyun.com/zh/oss/developer-reference/streaming-download-3?spm=a2c4g.11186623.0.0.59fe1290PZDhex
/// </summary>
public class AliOSSUploadService : ApiBase<RequestAliOSSUploadModel>
{
    static string endpoint = JsonConfig.JsonRead("MdAli:OSSAdvMdStorage:Endpoint");
    static string accessKeyId = JsonConfig.JsonRead("MdAli:AccessKeyId");
    static string accessKeySecret = JsonConfig.JsonRead("MdAli:AccessSecret");
    static string bucketName = JsonConfig.JsonRead("MdAli:OSSAdvMdStorage:BucketName");
    static AutoResetEvent _event = new AutoResetEvent(false);
    static OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);
    /// <summary>
    /// 执行
    /// </summary>
    protected override void ExecuteMethod()
    {
        if (string.IsNullOrWhiteSpace(Parameter.FilePath))
        {
            throw new AggregateException("本地文件路径不能为空");
        }

        using (var fs = File.Open(Parameter.FilePath, FileMode.Open))
        {
            var metadata = new ObjectMetadata();
            // 增加自定义元信息。
            //metadata.UserMetadata.Add("mykey1", "myval1");
            //metadata.UserMetadata.Add("mykey2", "myval2");
            //metadata.CacheControl = "No-Cache";
            //metadata.ContentType = "text/txt";
            string result = "Notice user: put object finish";

            // 异步上传。
            client.BeginPutObject(bucketName, Parameter.yunFilePath, fs, metadata, PutObjectCallback, result.ToCharArray());

            _event.WaitOne();
        }
    }
    /// <summary>
    /// 异步上传成功回调
    /// </summary>
    /// <param name="ar"></param>
    private void PutObjectCallback(IAsyncResult ar)
    {
        try
        {
            client.EndPutObject(ar);
            Console.WriteLine(ar.AsyncState as string);
            Console.WriteLine("Put object succeeded");
            Result.Msg = "success";
        }
        catch (Exception ex)
        {
            throw new AggregateException(ex.Message);
        }
        finally
        {
            _event.Set();
        }
    }
}

